﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using _14Net8AspNetCore_Authorization.Models;

namespace _14Net8AspNetCore_Authorization.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        /// <summary>
        /// 登入身份创建
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(LoginModel loginModel)
        {
            //1、创建身份 claimsIndentity
            //1.1 创建声明  用户描述 用户名 密码 角色
            // 总结：1、声明类型 给声明设置规范
            //       2、声明类型标准 给声明明确统一的规范
            if (loginModel.UserName.Contains("a"))
            {
                Claim claim = new Claim(ClaimTypes.Name, loginModel.UserName);
                Claim claim2 = new Claim("password", loginModel.Password);

                //1.2 创建声明集合
                var claims = new[] { claim, claim2 };

                //1.3 创建身份
                ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                //2、实现登录
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

                //3、返回
                return Ok("登录成功");
            }
            else
            {
                return Unauthorized("用户名或者密码错误");
            }

        }

        /// <summary>
        /// 获取登入信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("Login")]
        public async Task<IActionResult> Login()
        {

            string name = HttpContext.User.Identity.Name;
            Claim claim2 = HttpContext.User.Claims.FirstOrDefault(S => S.Type == "password");
            return Ok($"name:{name} password:{claim2?.Value}");
        }

        /// <summary>
        /// 注销登入
        /// </summary>
        /// <returns></returns>
        [HttpGet("LoginOut")]
        public async Task<IActionResult> LoginOut()
        {

            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Ok("注销成功");
        }
    }
}
